import '../../styles.css'

import RootLayout from "@/pages/components/Layout";
import styles from './index.module.css'
import Image from "next/image";
import Quiz from "@/pages/components/Quiz";
import redpacket from '../../../public/red.png'
import React, {useEffect, useRef, useState} from "react";
import {audioDetail, getSaleMan, queryUserInfo, wxSign} from "@/service/api";
import {useRouter} from "next/router";
import AudioPlayer from 'react-h5-audio-player';
import 'react-h5-audio-player/lib/styles.css';
import {getDomain, LAST_PLAYBACK_TIME} from "@/utils";
import play from '../../../public/play.png'
import pause from '../../../public/pause.png'
import red_packet from "../../../public/share/red_packet.png";

declare var wx: any;

export default function Audio() {
    const router = useRouter();
    // const [showModal, setShowModal] = useState(false);
    const [audio, setAudio] = useState<any>({})

    const audioRef = useRef<AudioPlayer | null>(null);
    const [lastTime, setLastTime] = useState(0); // 假设从localStorage或其他地方获取上次播放位置
    const [currentTime, setCurrentTime] = useState(0);
    const [totalTime, setTotalTime] = useState(0);  // 添加状态存储总时间
    const [isPlaying, setIsPlaying] = useState(false); // 初始状态为播放按钮
    const [showPlay, setShowPlay] = useState(false); // 初始状态为不显示播放按钮
    const [backgroundImageUrl, setBackgroundImageUrl] = useState<any>(null); // 初始背景图片

    const audioId = () => {
        let params = new URLSearchParams(window.location.search)
        console.log('audioId', params.get('audioId'))
        return params.get('audioId')
    }
    const wxUid = () => {
        let params = new URLSearchParams(window.location.search)
        return params.get('wxUid')
    }
    useEffect(() => {
        const interval = setInterval(() => {
            const id = audioId()
            if (audioRef.current && audioRef.current.audio.current && id) {
                setCurrentTime(audioRef.current.audio.current.currentTime);
                if (audioRef.current.audio.current.duration) {
                    setTotalTime(audioRef.current.audio.current.duration);
                }
                if (audioRef.current?.audio.current.currentTime > 0) {
                    localStorage.setItem(LAST_PLAYBACK_TIME + id, audioRef.current.audio.current.currentTime.toString());
                }
            }
        }, 1000); // 每秒更新一次

        return () => clearInterval(interval);
    }, []);
    // 更新显示剩余时间的逻辑
    const remainingTime = totalTime - currentTime;
    const remainingMinutes = Math.floor(remainingTime / 60);
    const remainingSeconds = Math.floor(remainingTime % 60);

    async function initAudio() {
        const userInfoRes = await queryUserInfo()
        if (userInfoRes.code !== 1) {
            return {msg: '获取用户信息失败,' + userInfoRes.msg}
        }
        if (userInfoRes.data.isBindSale !== 1) {
            //获取要绑定的销售信息
            const saleManRes = await getSaleMan({wxUid: wxUid() as string})
            if (saleManRes.code === 1) {
                // window.location.href = '/employee_qrcode?qr=' + encodeURIComponent(saleManRes.data.salesQrCode) + '&txt=未绑定老师，不可播放，请扫码咨询'
                return {url: '/employee_qrcode?qr=' + encodeURIComponent(saleManRes.data.salesQrCode) + '&txt=未绑定老师，不可播放，请扫码咨询'}
            } else {
                return {msg: '获取销售人员信息失败,' + saleManRes.msg}
            }
        }
        const params: API.AudioDetailParams = {
            audioId: audioId() as string,
            wxGid: null,
            wxUid: wxUid() as string,
        }
        const audioRes = await audioDetail(params)
        if (audioRes.code !== 1) {
            return {msg: '获取音频详情失败,' + audioRes.msg}
        }
        if (audioRes.data.isJumpAudio) {
            //前边有没听过的音频，直接跳过去
            return {url: '/audio?audioId=' + audioRes.data.jumpAudioId + '&wxUid=' + router.query.wxUid}
        }
        if (audioRes.data.isMatchSales !== null) {
            return {url: '/employee_qrcode?qr=' + encodeURIComponent(userInfoRes.data.salesQrCode) + '&txt=请从' + userInfoRes.data.salesName + '老师处收听音频'}
        }
        if (audioRes.data.isGroupPower === 0) {
            return {url: '/employee_qrcode?qr=' + encodeURIComponent(userInfoRes.data.salesQrCode) + '&txt=加入的微信群无播放权限，请扫码咨询'}
        }
        if (audioRes.data.quizStatus === 1) {
            //已答题未领红包
            return {url: '/quiz_result?audioId=' + audioRes.data.id + '&wxUid=' + router.query.wxUid}
        }
        setAudio(audioRes.data)
        //设置播放背景图
        if (audioRes.data.audioImage) {
            setBackgroundImageUrl(audioRes.data.audioImage)
        }

        return {data: audioRes.data, info: userInfoRes}
    }

    async function initTouchEvent() {
        function handleTouchStart(event: TouchEvent) {
            if (audioRef.current && audioRef.current.audio.current && !isPlaying) {
                console.log('touchstart')
                audioRef.current.audio.current.play()
                setTimeout(() => {
                    setIsPlaying(true)
                }, 500)

                window.removeEventListener('touchstart', handleTouchStart)
                console.log('touchstart removed')
                event.preventDefault()
            }
        }

        window.addEventListener('touchstart', handleTouchStart, {once: true})
    }

    async function initWxShare(userInfoRes: any, audio: any) {
        const script = document.createElement('script');
        script.src = "https://res.wx.qq.com/open/js/jweixin-1.6.0.js";
        script.onload = () => {
            console.log("微信JS-SDK加载完成")
            wxSign(window.location.href).then(res => {
                if (res.code !== 1) {
                    alert('获取微信签名失败,' + JSON.stringify(res))
                    return
                }
                console.log('wx sign', res)
                wx.config({
                    // debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                    appId: res.data.appId, // 必填，公众号的唯一标识
                    timestamp: res.data.timestamp, // 必填，生成签名的时间戳
                    nonceStr: res.data.nonceStr, // 必填，生成签名的随机串
                    signature: res.data.signature,// 必填，签名
                    jsApiList: [
                        'scanQRCode',
                        'checkJsApi',
                        'onMenuShareQQ',
                        'onMenuShareWeibo',
                        'onMenuShareQZone',
                        'getLocation',
                        'navigateToWeChat',
                        'navigateTo',
                        'onMenuShareAppMessage',
                        'onMenuShareTimeline',
                        'updateAppMessageShareData',
                        'updateTimelineShareData',
                    ] // 必填，需要使用的JS接口列表
                });

            }).catch(err => {
                alert('获取微信签名失败,' + JSON.stringify(err))
            })

            wx.ready(function () {
                // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
                console.log('share icon', getDomain() + '/share/red_packet.png')
                console.log('share name', audio.name)
                console.log('share uid', wxUid())
                const share_url = getDomain() + '/audio?audioId=' + audio.id + '&wxUid=' + router.query.wxUid + '&inviteId=' + userInfoRes.data.unionid
                console.log('share url', share_url)
                wx.updateAppMessageShareData({
                    title: audio.name, // 分享标题
                    desc: '百余期奖励等您来领|' + wxUid(), // 分享描述
                    link: share_url, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                    imgUrl: getDomain() + '/share/red_packet.png',// 分享图标
                    success: function () {
                        // 设置成功
                        console.log('updateAppMessageShareData success', audio.name, wxUid())
                    },
                    fail: function (res: any) {
                        console.log('updateAppMessageShareData fail', audio.name, wxUid(), JSON.stringify(res))
                    }
                })
                wx.updateTimelineShareData({
                    title: audio.name, // 分享标题
                    link: share_url, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                    imgUrl: `${red_packet}`, // 分享图标
                    success: function () {
                        // 设置成功
                        console.log('updateTimelineShareData success', audio.name, wxUid())
                    },
                    fail: function (res: any) {
                        console.log('updateTimelineShareData fail', audio.name, wxUid(), JSON.stringify(res))
                    }
                })
            });
            wx.error(function (res: any) {
                // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
            });
        };
        document.body.appendChild(script);

    }

    useEffect(() => {
        if (router.isReady) {
            initAudio().then((res) => {
                if (res.msg) {
                    alert(res.msg)
                    return
                }
                if (res.url) {
                    window.location.href = res.url
                    return
                }

                initTouchEvent().then(() => {
                    console.log('touch event inited')
                })

                const savedTime = localStorage.getItem(LAST_PLAYBACK_TIME + res.data.id);
                if (savedTime) {
                    setLastTime(Number(savedTime));
                } else {
                    setLastTime(0)
                }

                initWxShare(res.info, res.data).then(() => {
                    console.log('wx share inited')
                })
            })
        }
    }, [router.isReady]);

    //当用户离开页面时，保存当前播放位置
    // useEffect(() => {
    //     const savePlaybackTime = () => {
    //         alert('调试信息：页面即将关闭，保存播放位置')
    //         if (audioRef.current) {
    //             localStorage.setItem(LAST_PLAYBACK_TIME + audioId(), audioRef.current?.audio.current?.currentTime ? audioRef.current?.audio.current?.currentTime.toString() : '0');
    //         }
    //     };
    //     window.addEventListener('beforeunload', savePlaybackTime);
    //     return () => {
    //         window.removeEventListener('beforeunload', savePlaybackTime);
    //     };
    // }, []);

    // 当音频加载后，设置播放位置
    useEffect(() => {
        if (audioRef.current && lastTime > 0) {
            audioRef.current!!.audio.current!!.currentTime = lastTime;
            // Optional: 自动播放
            // audioRef.current.play();
        }
    }, [lastTime]);

    // useEffect(() => {
    //     const handleVisibilityChange = () => {
    //         if (document.visibilityState === 'hidden') {
    //             if (audioRef.current && audioRef.current.audio.current) {
    //                 audioRef.current.audio.current.pause(); // 暂停音频
    //             }
    //         } else if (document.visibilityState === 'visible') {
    //             if (audioRef.current && audioRef.current.audio.current && isPlaying) {
    //                 audioRef.current.audio.current.play(); // 恢复音频
    //             }
    //         }
    //     };
    //
    //     document.addEventListener('visibilitychange', handleVisibilityChange);
    //
    //     return () => {
    //         document.removeEventListener('visibilitychange', handleVisibilityChange);
    //     };
    // }, [isPlaying]);


    function jumpToQuiz(audioId: number, wxUid: string) {
        if (audio.quizStatus === 3) {
            //已领取过红包，则不能重复答题
            // alert('您已经领取过红包，不能重复答题')
            return
        }
        if (audio.quizStatus === 2) {
            //已经答过题，不能重复答题
            // alert('您已经答错3次，不能重复答题')
            return
        }

        const domain = getDomain()
        window.location.href = domain + '/quiz?audioId=' + audioId + '&wxUid=' + wxUid
    }

    const playAudio = () => {
        console.log('play btn clicked', isPlaying)
        const audioPlayer = audioRef.current?.audio.current;
        if (audioPlayer) {
            audioPlayer.play();
            setIsPlaying(true);
        }
        return false
    };

    const pauseAudio = () => {
        console.log('pause btn clicked', isPlaying)
        const audioPlayer = audioRef.current?.audio.current;
        if (audioPlayer) {
            audioPlayer.pause();
            setIsPlaying(false);
        }
        return false
    };

    return (
        <RootLayout>
            <div className={styles.audio}>
                <div className={styles.audio_cover}>
                    <div className={styles.audio_container}
                         style={{backgroundImage: `url(${backgroundImageUrl})`}}
                    >
                        {
                            audio ? (<AudioPlayer
                                key={audio.id}
                                ref={audioRef}
                                className={styles.audio_player}
                                autoPlay={false}
                                src={audio.filePath}
                                onPlay={e => {
                                    console.log("onPlay")
                                    // setIsPlaying(true)
                                }}
                                onPause={e => {
                                    console.log("onPause")
                                    // setIsPlaying(false)
                                }}
                                onEnded={e => {
                                    setIsPlaying(false)
                                    jumpToQuiz(audio.id, wxUid() as string)
                                }}
                                // onCanPlay={e => {
                                //     // audioRef.current?.audio.current?.play()
                                //     if (audioRef.current?.audio.current?.duration) {
                                //         setTotalTime(audioRef.current?.audio.current?.duration);
                                //         setShowPlay(true)
                                //         setIsPlaying(false)
                                //     }
                                // }}
                                onLoadedMetaData={e => {
                                    // audioRef.current?.audio.current?.play()
                                    if (audioRef.current?.audio.current?.duration) {
                                        setTotalTime(audioRef.current?.audio.current?.duration);
                                        setShowPlay(true)
                                        setIsPlaying(false)
                                    }
                                }}
                            />) : null
                        }
                        {
                            audio ? (<input id="audio_id" type={"text"} hidden={true} value={audio.id}/>) : null
                        }
                        <div
                            className={styles.currentTime}>{remainingMinutes}:{('0' + remainingSeconds).slice(-2)}</div>
                        <div className={styles.controls}>
                            {/*<button onClick={() => audioRef.current?.audio.current?.play()}>播放</button>*/}
                            {/*<button onClick={() => audioRef.current?.audio.current?.pause()}>暂停</button>*/}
                            {
                                showPlay && (!isPlaying ?
                                    (<button id={'btn_play'} onClick={playAudio} className={styles.play}>
                                        <Image src={play} alt="Play" width={50} height={50}/>
                                    </button>)
                                    :
                                    (<button onClick={pauseAudio} className={styles.pause}>
                                        <Image src={pause} alt="Pause" width={50} height={50}/>
                                    </button>))
                            }
                        </div>
                    </div>
                </div>
                {
                    audio && audio.quizStatus === 3 ? (
                        <div className={styles.tips}>
                            该音频已领取红包，收听后不能重复做题领红包～
                            可以从群里收听新的音频来获取红包
                        </div>
                    ) : <></>
                }
                {
                    audio && audio.quizStatus === 2 ? (
                        <div className={styles.tips}>
                            答错3次，当前音频不能再答题了
                        </div>
                    ) : <></>
                }
                {
                    audio && audio.quizStatus !== 3 && audio.quizStatus !== 2 ? (
                        <>
                            <div className={styles.audio_title}>
                                音频：{audio.name}
                            </div>
                            <div>
                                {
                                    audio.questions ? audio.questions.map((question: any, index: number) => (
                                        <Quiz key={index} index={index} question={question} canSelect={false}
                                              onSelectChange={(options) => {
                                              }}/>
                                    )) : null
                                }
                            </div>
                            <div className={styles.redpacket_container}>
                                <Image className={styles.redpacket} src={redpacket} alt={'红包'}/>
                            </div>
                        </>
                    ) : <></>
                }

            </div>
            <div onClick={() => {
                window.location.href = '/my'
            }} className={styles.homeBtn}>首页
            </div>
        </RootLayout>
    )
}
